package com.mazaiting.course.controller;

import com.mazaiting.course.domain.Response;
import com.mazaiting.course.exception.CustomException;
import com.mazaiting.course.exception.ExceptionEnum;
import com.mazaiting.course.service.LoginService;
import com.mazaiting.course.utils.RegexMatchesUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/***
 * 多文件上传
 * @author mazaiting
 * @datetime 2022/3/8
 */
@RestController
@RequestMapping("/upload")
public class UploadController {


    @Resource
    private LoginService loginService;


    /**
     * 单文件上传
     */
    @PostMapping("/single")
    public Response single(@RequestParam("fileName") MultipartFile file, @RequestParam Map<String,String> map)  {
        Set<Map.Entry<String, String>> entries = map.entrySet();
        // 此处传进来的参数可能是
        // 0 或者 多个
        // 可能是非法
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            if(StringUtils.isEmpty(key)){
                throw new CustomException(ExceptionEnum.PARAM_ILLEGA);
            }
            if(StringUtils.isEmpty(value)){
                throw new CustomException(ExceptionEnum.PARAM_ILLEGA);
            }
            RegexMatchesUtils.isMatchesSecret(key);
            RegexMatchesUtils.isMatchesSecret(value);
        }

        /**
         *
         * 文件路径
         */
        // 判断文件是否为空
        if (file.isEmpty()) {
            // 文件为空
            throw new CustomException(ExceptionEnum.FILE_NULL);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件大小
        long size = file.getSize();
        // 判断文件夹路径是否存在
        // filePath = C:/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/
        String filePath = loginService.getFilePath();
        // 创建文件夹路径
        // fileDir = C:/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/studentWork
        File fileDir = new File(filePath,"data");
        // 判断是否存在
        if (!fileDir.exists()) {
            // 文件夹遍历创建
            fileDir.mkdirs();
        }

        // 判断否为路径
        if (fileDir.isDirectory()) {
            // 创建目标文件
            File destFile = new File(fileDir + "/" + System.currentTimeMillis() + "_" + fileName);
            try {

                // 保存文件
                file.transferTo(destFile);
                return new Response(1, "文件存储成功!");
            } catch (IOException | IllegalStateException e) {
                return new Response(0, "文件存储异常!");
            }
        }

        return new Response(0, "请检查文件路径是否存在!");
    }

    /**
     * 多文件上传
     */
    @PostMapping("/multiFileUpload")
    public Response multiFileUpload(MultipartFile[] files,String key, String value) {
        // 非空判断
        if(StringUtils.isEmpty(key)){
            throw new CustomException(ExceptionEnum.PARAM_ILLEGA);
        }
        if(StringUtils.isEmpty(value)){
            throw new CustomException(ExceptionEnum.PARAM_ILLEGA);
        }

        // 非法值校验
        RegexMatchesUtils.isMatchesSecret(key);
        RegexMatchesUtils.isMatchesSecret(value);
        // 获取文件
//        List<MultipartFile> files = request.getMultiFileMap().get("fileName[]");
        List<Response> responses = new ArrayList<>();
        // 过滤空文件
        Stream<MultipartFile> multipartFileStream = Arrays.stream(files).filter((file) -> !file.isEmpty());
        List<MultipartFile> multipartFiles = multipartFileStream.collect(Collectors.toList());
//        files = (MultipartFile[]) multipartFileStream.toArray();
        if(multipartFiles.size()==0){
            throw new CustomException(ExceptionEnum.FILE_NULL);
        }

        // filePath = C:/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/
        String filePath = loginService.getFilePath();
        // 创建文件路径
        // fileDir = C:/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/studentWork
        File fileDir = new File(filePath,"data");
        // 判断是否存在
        if (!fileDir.exists()) {
            // 文件夹遍历创建
            fileDir.mkdirs();
        }


        multipartFiles.forEach(file ->{
            String fileName = file.getOriginalFilename();
            try(
                // 2.创建高效ioStream读取文件
                InputStream io = new BufferedInputStream(file.getInputStream());
                // 3.创建高效osStream写入文件
                OutputStream os = new BufferedOutputStream(new FileOutputStream(fileDir+"/"+System.currentTimeMillis()+fileName))
            ) {
                byte [] bys = new byte[1024];
                int len;
                while ((len = io.read(bys)) !=-1){
                    os.write(bys,0,len);
                    os.flush();
                }
            } catch (IOException e) {
                responses.add(new Response(ExceptionEnum.UPLOAD_ERROR));
            }
            responses.add(new Response(ExceptionEnum.UPLOAD_FILE_SUCCESS));
        });
        return Response.Success().setData(responses);
    }


}
